package Controller;

import Dao.DepartmentDao;
import Model.Department;
import Model.DepartmentChanged;
import Service.DepartmentService;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/department")
public class DepartmentController {
    private static final Logger logger = LoggerFactory.getLogger(DepartmentController.class);
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    DepartmentDao departmentDao;
//    @Resource
//    private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(DepartmentController.class);// 日志文件
    /**
     * 机构列表
     * @return
     */
    @RequestMapping("/showDepartmentInfo")
    @ResponseBody
    public PageInfo getDepartmentInfo(@RequestParam(value = "pn", defaultValue = "1") Integer pn, @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        PageHelper.startPage(pn, limit);
        List<Department> departmentInfos = departmentService.getAllDepartmentList();
        PageInfo page = new PageInfo(departmentInfos);
        return page;
    }

    @RequestMapping("/showDepartmentChangedInfo")
    @ResponseBody
    public PageInfo getDepartmentChangedInfo(@RequestParam(value = "pn", defaultValue = "1") Integer pn, @RequestParam(value = "limit", defaultValue = "10") Integer limit) {
        PageHelper.startPage(pn, limit);
        List<DepartmentChanged> departmentchangeds = departmentService.getAllDepartmentChangedList();
        PageInfo page = new PageInfo(departmentchangeds);
        return page;
    }

    /**
     * 删除机构
     */
    @RequestMapping(value = "/delDepartment", method = RequestMethod.POST)
    @ResponseBody
    public String delRole(@RequestParam("id") int id) {
        logger.debug("删除机构以及它对应的权限--id-" + id);
        try {
            if (id > 0) {
                return departmentService.delDepartment(id);
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除机构异常！", e);
        }
        return "删除机构出错，请您稍后再试";
    }

    /**
     * 搜索机构/信息页面
     * @param departmentName
     * @param regionCode
     * @param status
     * @return
     */
    @RequestMapping("/searchDepartment")
    @ResponseBody
    public PageInfo searchDepartmentInfo(@RequestParam(value = "pn", defaultValue = "1") Integer pn,
                                         @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                         @RequestParam(value = "departmentName") String departmentName, @RequestParam(value="regionCode")String regionCode,
                                         @RequestParam(value="status")String status) {
        System.out.println(departmentName);
        System.out.println(regionCode);
        System.out.println(status);

        if (departmentName == "" && regionCode =="" && status =="") {
            System.out.println("搜索框无数据");
            PageHelper.startPage(pn, limit);
            List<Department> department = departmentService.getAllDepartmentList();
            PageInfo page = new PageInfo(department);
            return page;
        }
        else{
            System.out.println("contoller层：搜索框非空");
            PageHelper.startPage(pn, limit);
            List<Department> department = departmentService.findDepartmentInfo(departmentName,regionCode,status);
            System.out.println("controller层：搜索成功");
            PageInfo page = new PageInfo(department);
            System.out.println(page);
            return page;
        }
    }


    /**
     * 搜索机构/变更页面
     * @param nameSearch
     * @param settleCodeSearch
     * @param titleSearch
     * @return
     */
    @RequestMapping("/searchChangedInfo")
    @ResponseBody
    public PageInfo searchChangedInfo(@RequestParam(value = "pn", defaultValue = "1") Integer pn,
                                      @RequestParam(value = "limit", defaultValue = "10") Integer limit,
                                      @RequestParam(value = "nameSearch") String nameSearch,
                                      @RequestParam(value="settleCodeSearch")String settleCodeSearch,
                                      @RequestParam(value="titleSearch")String titleSearch) {
        System.out.println("controller层："+nameSearch);
        System.out.println("controller层："+settleCodeSearch);
        System.out.println("controller层："+titleSearch);

        if (nameSearch == "" && settleCodeSearch =="" && titleSearch =="") {
            System.out.println("搜索框无数据");
            PageHelper.startPage(pn, limit);
            List<DepartmentChanged> changedInfo = departmentService.getAllDepartmentChangedList();
            PageInfo page = new PageInfo(changedInfo);
            return page;
        }
        else{
            System.out.println("contoller层：搜索框非空");
            PageHelper.startPage(pn, limit);
            List<DepartmentChanged> changedInfo = departmentService.findChangedInfo(nameSearch,settleCodeSearch,titleSearch);
            System.out.println("controller层：搜索成功");
            PageInfo page = new PageInfo(changedInfo);
            System.out.println(page);
            return page;
        }
    }

    /**
     * 更新机构数据
     */
    @RequestMapping(value = "/updateDepartment", method = RequestMethod.POST,produces={"application/json;charset=UTF-8"})
    @ResponseBody
    public String updateDepartment(Department department, HttpSession session) {
        try {
            System.out.println("开始更新");
            String abc=departmentService.updateDepartment(department, session);
            System.out.println("controller层返回："+abc);
            if(abc=="ok"){
                return "{\"msg\":\"ok\"}";
            }else{
                return "{\"msg\":\"error\"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("更新异常！", e);
            return "操作异常，请您稍后再试";
        }
    }


    @RequestMapping(value = "/AddDepartment")
    @ResponseBody
    public String AddElder(HttpServletRequest request, HttpServletResponse response, HttpSession session) {
        System.out.println("开始添加机构");
        Department department=new Department();
        department.setDepartment_name(request.getParameter("department_name"));
        System.out.println("Department_name："+department.getDepartment_name());

        department.setDepartment_phone_number(request.getParameter("department_phone_number"));
        department.setDepartment_address(request.getParameter("department_address"));
        department.setDepartment_corporate(request.getParameter("department_corporate"));
        department.setDepartment_region_code(request.getParameter("department_region_code"));

        System.out.println("Department_region_code："+department.getDepartment_region_code());
        //department.setDepartment_notification_date(request.getParameter("department_notification_date"));
        department.setDepartment_settlement_code(request.getParameter("department_settlement_code"));
        department.setDepartment_settlement_scope(request.getParameter("department_settlement_scode"));
        //department.setDepartment_first_time(request.getParameter("department_first_time"));
        department.setDepartment_status(request.getParameter("department_status"));
        try {
            System.out.println("机构添加"+department.getDepartment_region_code());
            departmentDao.createDeparmentInfo(department);
            System.out.println("机构添加成功"+department.getDepartment_name());
            return "{\"msg\":\"ok\"}";
            //status = 0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "{\"msg\":\"error\"}";


    }

    /**
     * 导入Excel获取机构数据
     */
    @RequestMapping(value = "/InputExcel")
    @ResponseBody
    public String InputExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        String flag = "02";// 上传标志
        System.out.println("进入controller层 导入excel");
        System.out.println("file文件："+file);
        if (!file.isEmpty()) {
            try {
                String originalFilename = file.getOriginalFilename();// 原文件名字
                System.out.println("文件名：" + originalFilename);
                InputStream is = file.getInputStream();// 获取输入流
                flag = departmentService.InputExcel(is, originalFilename);
                System.out.println("controller层：上传成功，flag= "+flag);
                return "{\"msg\":\"ok\"}";
            } catch (Exception e) {
                flag = "03";// 上传出错
                e.printStackTrace();
                System.out.println("controller层：上传失败，flag= "+flag);
            }
        }
        return "{\"msg\":\"error\"}";
    }

    /**
     * 信息页面/导出信息
     * @param departmentName
     * @param regionCode
     * @param status
     * @return
     */
    @RequestMapping("/ExportAllInfo")
    @ResponseBody
    public List<Department> DeapartmentInfo(@RequestParam(value = "departmentName") String departmentName,
                                            @RequestParam(value="regionCode")String regionCode,
                                            @RequestParam(value="status")String status){
        System.out.println("进入controller层");
        if (departmentName == "" && regionCode =="" && status =="") {
            System.out.println("搜索框无数据");
            List<Department> department = departmentService.getAllDepartmentList();
            return department;
        }
        else{
            System.out.println("contoller层：搜索框非空");
            List<Department> department = departmentService.findDepartmentInfo(departmentName,regionCode,status);
            System.out.println("controller层：搜索成功");
            System.out.println(department);
            return department;
        }
    }

    /**
     * 变更页面/导出信息
     * @param nameSearch
     * @param settleCodeSearch
     * @param titleSearch
     * @return
     */
    @RequestMapping("/ExportAllChangedInfo")
    @ResponseBody
    public List<DepartmentChanged> ExportAllChangedInfo(@RequestParam(value = "nameSearch") String nameSearch,
                                            @RequestParam(value="settleCodeSearch")String settleCodeSearch,
                                            @RequestParam(value="titleSearch")String titleSearch){
        System.out.println("进入controller层");
        if (nameSearch == "" && settleCodeSearch =="" && titleSearch =="") {
            System.out.println("搜索框无数据");
            List<DepartmentChanged> departmentChangeds = departmentService.getAllDepartmentChangedList();
            return departmentChangeds;
        }
        else{
            System.out.println("contoller层：搜索框非空");
            List<DepartmentChanged> departmentChangeds = departmentService.findChangedInfo(nameSearch,settleCodeSearch,titleSearch);
            System.out.println("controller层：搜索成功");
            System.out.println(departmentChangeds);
            return departmentChangeds;
        }
    }
}



